package org.example.core.io;

import org.example.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: luyg
 * @Date: 2024/09/06/12:52
 * @Description:
 */
public class ClassPathResource implements Resource{
    private final String path;
    private ClassLoader classLoader;
    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path,ClassLoader classLoader){
        this.path=path;
        this.classLoader=(classLoader!=null?classLoader: ClassUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream resourceAsStream = classLoader.getResourceAsStream(path);
        if(resourceAsStream ==null){
            throw new FileNotFoundException(
                    this.path + " cannot be opened because it does not exist");
        }
        return resourceAsStream;
    }
}
